<template>
  <com-header :title="title"></com-header>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="addressData.name"
        name="姓名"
        label="姓名"
        placeholder="收货人姓名"
        :rules="[{ required: true, message: '请填写收货人姓名' }]"
      />
      <van-field
        v-model="addressData.phone"
        name="电话"
        label="电话"
        placeholder="收货人手机号"
        :rules="[{ required: true, message: '请填写收货人手机号' }]"
      />
      <van-field
        v-model="addressData.address"
        is-link
        readonly
        name="area"
        label="地区"
        placeholder="选择省/市/区"
        @click="showArea = true"
      />
      <van-popup v-model:show="showArea" position="bottom">
        <van-area
          :area-list="areaList"
          @confirm="onConfirm"
          @cancel="showArea = false"
        />
      </van-popup>
      <van-field
        v-model="addressData.detail"
        name="detail"
        label="详细地址"
        placeholder="街道门牌、楼层房间号等信息"
        :rules="[{ required: true, message: '请填写详细地址' }]"
      />
      <van-field name="switch" label="设为默认收货地址" label-width="150px">
        <template class="text-right" #input>
          <van-switch v-model="addressData.default" size="20" />
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        {{ id > 0 ? "保存" : "提交" }}
      </van-button>

      <van-button round block type="default" class="m-t-10" @click="delAddress">
        删除
      </van-button>
    </div>
  </van-form>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "@/stores/store";
import { areaList } from "@vant/area-data";
import type { IAddress } from "@/types";
import { fnMsg, fnDialog } from "@/plugins/common";
export default defineComponent({
  setup() {
    const route = useRoute(),
      router = useRouter(),
      store = useStore();
    const title = ref(route.query.title),
      showArea = ref(false),
      addressData = ref<IAddress>({
        default: false,
        name: "",
        address: "",
        detail: "",
        phone: "",
      });
    const id: number = Number(route.params.id);
    const onConfirm = (areaValues: any) => {
      showArea.value = false;
      addressData.value.address = areaValues
        .filter((item: any) => !!item)
        .map((item: any) => item.name)
        .join("/");
    };
    // 添加或修改
    const onSubmit = () => {
      let { name, address, detail, phone } = addressData.value;
      let list = store.state.addressData.list;
      if (id > 0) {
        // 修改
        let index = list.findIndex((item: any) => id == item.id);
        let target = list[index];
         if (addressData.value.default) {
            list.filter((it: IAddress) => it.id != id).forEach((item: IAddress)  => {
              item.default = false;
            })
            target = {
              name,
              address,
              detail,
              phone,
              default: true,
              id: id,
          };
        } else {
          target = {
            name,
            address,
            detail,
            phone,
            default: false,
            id: id,
          };
        }
        
        list[index] = { ...target };
        store.commit("addAddress", list);
        fnMsg("修改成功!");
      } else {
        // 添加
        let index = list.findIndex((item: IAddress) => detail == item.detail);
        if (index == -1) {
          if (addressData.value.default) {
            list.forEach((item: IAddress)  => {
              item.default = false;
            })
            list.push({
              name,
              address,
              detail,
              phone,
              default: true,
              id: store.state.addressData.list.length + 1,
            });
          } else {
            list.push({
              name,
              address,
              detail,
              phone,
              default: false,
              id: store.state.addressData.list.length + 1,
            });
          }
          store.commit("addAddress", list);
          fnMsg("添加成功!");
          router.push({
            name: 'address'
          });
        } else {
          fnMsg("收货地址已存在!");
          return;
        }
      }
    };
    // 删除
    const delAddress = () => {
      let list = store.state.addressData.list;
      fnDialog("提示", "确认删除此收货地址吗?")
        .then(() => {
          let index = list.findIndex((item: any) => id == item.id);
          list.splice(index, 1);
          store.commit("addAddress", list);
          fnMsg("删除成功!");
          router.push({
            name: 'address'
          });
        })
        .catch(() => {
          fnMsg("取消删除");
        });
    };
    onMounted(() => {
      if (id > 0) {
        addressData.value = store.state.addressData.list.find(
          (item: IAddress) => item.id == id
        );
      }
    });
    return {
      id,
      title,
      areaList,
      addressData,
      showArea,
      onConfirm,
      onSubmit,
      delAddress,
    };
  },
});
</script>
